<template>
  <div class="container">
    <div class="formWrapper">
      <div class="formItems px-3">
        <div class="formItem justify-center">
          <n-spin size="small">
            <template #description>
              <div class="tip">自动登录中</div>
            </template>
          </n-spin>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from "vue";
import request from "@/utils/request";
import { useRouter } from "vue-router";
import { RequestError, RequestErrorTypes } from "@/utils/RequestError";

const message = useMessage();
window.$message = useMessage();
const router = useRouter();

onMounted(() => {
  // 验证TGC是否有效
  request({
    method: "POST",
    url: "/auth/validateTgc",
    withCredentials: true,
  })
    .then(async () => {
      let redirect = window.localStorage.getItem("redirect");
      if (redirect !== null) {
        // 向服务器请求签发ST
        await request<string>({
          method: "POST",
          url: "/auth/getSt",
          data: {
            target: redirect,
          },
        }).catch((e) => {
          window.localStorage.removeItem("redirect");
          if (e instanceof RequestError) {
            const { errCode } = e;
            if (errCode === RequestErrorTypes.BAD_REQUEST) {
              router.push({
                name: "400",
                state: {
                  redirect,
                },
                replace: true,
              });
            } else if (errCode === RequestErrorTypes.FORBIDDEN) {
              router.replace("/403");
            }
          }
        });
      } else {
        router.push("/noRedirectUrl");
      }
    })
    .catch(() => {
      window.localStorage.removeItem("authorized");
      router.push("/");
    });
});
</script>

<style scoped lang="scss">
.container {
  width: 100vw;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  color: #333639;
  font-family: "Microsoft YaHei", Helvetica, "PingFang SC";
}

.tip {
  margin-top: 10px;
  font-size: 13px;
  color: #333639;
}

.px-3 {
  padding-left: 3px !important;
  padding-right: 3px !important;
}

.formWrapper {
  width: 380px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  .formItems {
    display: flex;
    flex-direction: column;
    gap: 30px;
    padding-top: 25px;
    > .formItem {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }
}

.justify-center {
  justify-content: center;
}

.items-center {
  align-items: center;
}

.flex {
  display: flex;
}

.flex-col {
  flex-direction: column;
}

.select-none {
  user-select: none;
}
</style>
